#!/usr/bin/python3
# -*- coding: UTF-8 -*-


import os  # 文件相关操作
import sys
from tkinter import font  # 额外接受参数操作
import openpyxl  # xlsx表格操作
from docx import Document  # docx文档操作
# from utils import ExcelParse  # 封装的Excel读取
from docx.shared import Cm, Pt  # 设置docx文档字体大小样式
from datetime import datetime  # 时间
# from utils.TextTemplate import *  # 评语模板相关
# from utils import Instructor  # 第一个窗体的UI
# from utils import Instructor2  # 第二个窗体的UI
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT  # 表格样式设计操作
from textrank4zh import TextRank4Keyword, TextRank4Sentence  # 从文本从提取关键词、句相关
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QFileDialog, QTableWidgetItem, QHeaderView  # 窗体工具相关
import time

# 更新分数
def updateScore(record , startTime , endTime):
    name = record['studentName']
    title = record['title'].replace('/','')
    number = record['number']
    defenseScore = record['defenseScore']
    thesisScore = record['thesisScore']
    if os.path.exists(f'{getRunFilePath()}/GenerateWord/{number}{name}/{title}.docx'):
         # 通过路径读取word 模版内容
        # document = Document(os.path.join(f'{getRunFilePath()}Template', '指导教师审查意见.docx'))
        document = Document(os.path.join(f'{getRunFilePath()}/GenerateWord/{number}{name}/{title}.docx'))
        table = document.tables[0]

        # 答辩小组分数评定
        # 修改表格中中文样式
        row16 = table.rows[15]
        row16.cells[1].text = '三、答辩小组对学生答辩成绩的评定（百分制）：'
        paragraphs = table.rows[15].cells[0].paragraphs[0]
        #####################################################
        run = paragraphs.add_run('   ' + defenseScore + '   ')
        run.font.underline = True
        run.font.name = '宋体'
        run.font.size = Pt(13)
        paragraphs.add_run('分')

        # 最终成绩
        # 修改表格中中文样式
        row18 = table.rows[17]
        row18.cells[7].text = '成绩(百分制)：'
        paragraphs = table.rows[17].cells[7].paragraphs[0]
        #####################################################
        run = paragraphs.add_run('   ' + thesisScore + '   ')
        run.font.underline = True
        run.font.name = '宋体'
        run.font.size = Pt(13)
        paragraphs.add_run('分')

        # 时间调整
        currentRow = table.rows[2]
        currentRow.cells[1].text = ''
        paragraphs = currentRow.cells[1].paragraphs[0]
        runF = paragraphs.add_run('  2022 ')
        runF.font.underline = True
        runF.font.name = 'Calibri'
        runF.font.size = Pt(12)
        nian = paragraphs.add_run('年')
        nian.font.name = '宋体'
        nian.font.size = Pt(12)
        run1 = paragraphs.add_run(' 5 ')
        run1.font.underline = True
        run1.font.name = 'Calibri'
        run1.font.size = Pt(12)
        yue = paragraphs.add_run('月')
        yue.font.name = '宋体'
        yue.font.size = Pt(12)
        run2 = paragraphs.add_run(' 29 ')
        run2.font.underline = True
        run2.font.name = 'Calibri'
        run2.font.size = Pt(12)
        ri = paragraphs.add_run('日')
        ri.font.name = '宋体'
        ri.font.size = Pt(12)
        startDateStr = paragraphs.add_run(' ' + startTime)
        startDateStr.font.name = 'Calibri'
        startDateStr.font.size = Pt(12)
        fh = paragraphs.add_run('～')
        fh.font.name = '宋体'
        fh.font.size = Pt(13)
        endDateStr = paragraphs.add_run(endTime)
        endDateStr.font.name = 'Calibri'
        endDateStr.font.size = Pt(12)

        setFontStyle(row16)
        setFontStyle(row18)
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord'):
            os.mkdir(f'{getRunFilePath()}/GenerateWord')
        # 判断文件是否存在
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord/{number}{name}'):
            # 文件不再存在则创建文件
            os.mkdir(f'{getRunFilePath()}/GenerateWord/{number}{name}')
        #####################################################
        title = title.replace('/' , '')
        timeStr = time.time()
        # print(f'文件路径：{getRunFilePath()}/GenerateWord/{number}{name}/{title}{timeStr}.docx')
        document.save(os.path.join(f"{getRunFilePath()}/GenerateWord/{number}{name}",
                                    f'{title}{timeStr}.docx'))
        return f"{getRunFilePath()}/GenerateWord/{number}{name}/{title}{timeStr}.docx"

# 时间调整
def timeAdjustment(record , startTime , endTime):
    name = record['studentName']
    title = record['title'].replace('/','')
    if os.path.exists(f'{getRunFilePath()}/GenerateWord/{name}/{title}.docx'):
         # 通过路径读取word 模版内容
        document = Document(os.path.join(f'{getRunFilePath()}/GenerateWord/{name}/{title}.docx'))
        table = document.tables[0]

        # 答辩时间
        currentRow = table.rows[2]
        currentRow.cells[1].text = ''
        paragraphs = currentRow.cells[1].paragraphs[0]
        run = paragraphs.add_run('  2022 ')
        run.font.underline = True
        run.font.name = 'Calibri'
        run.font.size = Pt(12)
        nian = paragraphs.add_run('年')
        nian.font.name = '宋体'
        nian.font.size = Pt(12)
        run1 = paragraphs.add_run(' 5 ')
        run1.font.underline = True
        run1.font.name = 'Calibri'
        run1.font.size = Pt(12)
        yue = paragraphs.add_run('月')
        yue.font.name = '宋体'
        yue.font.size = Pt(12)
        run2 = paragraphs.add_run(' 29 ')
        run2.font.underline = True
        run2.font.name = 'Calibri'
        run2.font.size = Pt(12)
        ri = paragraphs.add_run('日')
        ri.font.name = '宋体'
        ri.font.size = Pt(12)
        startDateStr = paragraphs.add_run(' ' + startTime)
        startDateStr.font.name = 'Calibri'
        startDateStr.font.size = Pt(12)
        fh = paragraphs.add_run('～')
        fh.font.name = '宋体'
        fh.font.size = Pt(13)
        endDateStr = paragraphs.add_run(endTime)
        endDateStr.font.name = 'Calibri'
        endDateStr.font.size = Pt(12)
        print(f'段落：{paragraphs.text}')
        #####################################################
        # run = paragraphs.add_run('   ' + defenseScore + '   ')
        # run.font.underline = True
        # run.font.name = '宋体'
        # run.font.size = Pt(13)
        # paragraphs.add_run('分')

        # 最终成绩
        # 修改表格中中文样式
        #####################################################
        # run = paragraphs.add_run('   ' + thesisScore + '   ')
        # run.font.underline = True
        # run.font.name = '宋体'
        # run.font.size = Pt(13)
        # paragraphs.add_run('分')
        # setFontStyle(row16)
        # setFontStyle(row18)
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord'):
            os.mkdir(f'{getRunFilePath()}/GenerateWord')
        # 判断文件是否存在
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord/{name}'):
            # 文件不再存在则创建文件
            os.mkdir(f'{getRunFilePath()}/GenerateWord/{name}')
        #####################################################
        title = title.replace('/' , '')
        timeStr = str(time.time())
        document.save(os.path.join(f"{getRunFilePath()}/GenerateWord/{name}",
                                    f'{title}{timeStr}.docx'))
        return f"{getRunFilePath()}/GenerateWord/{name}/{title}{timeStr}.docx"

    
def generateWord(record):
    '''
    生成文档
    Returns
    -------
    无
    '''
    try:
        studentName = record['studentName']
        title = record['title']
        className = record['class']
        request1 = record['request1']
        request2 = record['request2']
        request3 = record['request3']
        ask1 = record['ask1']
        ask2 = record['ask2']
        ask3 = record['ask3']
        number = record['number']
        defenseScore = record['defenseScore']
        thesisScore = record['thesisScore']
        # 通过路径读取word 模版内容
        # document = Document(os.path.join(f'{getRunFilePath()}Template', '指导教师审查意见.docx'))
        document = Document(os.path.join(f'{getRunFilePath()}/template','长江大学工程技术学院毕业设计成绩评定.docx'))
        table = document.tables[0]
        #####################################################
        row1 = table.rows[0]
        for itm in range(len(row1.cells)):
            if itm >= 1 and itm < 2:
                ''' 学生姓名 '''
                row1.cells[itm].text = studentName
            elif itm > 5 and itm <= 6:
                ''' 专业班级 '''
                row1.cells[itm].text = className

        row2 = table.rows[1]
        for itm in range(len(row2.cells)):
            if itm >= 1 and itm <= 6:
                ''' 毕业设计(论文)题目 '''
                row2.cells[itm].text = title
        # 追加问题
        # 答辩小组问题、问题一
        #####################################################       
        run = table.rows[9].cells[0].paragraphs[0].add_run(request1)
        row10 = table.rows[9]
        # 答辩回答情况评判
        row10.cells[7].text = ask1
        # 答辩小组问题、问题二
        #####################################################
        run = table.rows[10].cells[0].paragraphs[0].add_run(request2)
        row11 = table.rows[10]
        # 答辩回答情况评判
        row11.cells[7].text = ask2
        # 答辩小组问题、问题三
        #####################################################
        run = table.rows[11].cells[0].paragraphs[0].add_run(request3)
        row12 = table.rows[11]
        # 答辩回答情况评判
        row12.cells[7].text = ask3

        # 答辩小组分数评定
        # 修改表格中中文样式
        row16 = table.rows[15]
        row16.cells[1].text = '三、答辩小组对学生答辩成绩的评定（百分制）：'
        paragraphs = table.rows[15].cells[0].paragraphs[0]
        #####################################################
        run = paragraphs.add_run('   ' + defenseScore + '   ')
        run.font.underline = True
        run.font.name = '宋体'
        run.font.size = Pt(13)
        paragraphs.add_run('分')

        # 最终成绩
        # 修改表格中中文样式
        row18 = table.rows[17]
        row18.cells[7].text = '成绩(百分制)：'
        paragraphs = table.rows[17].cells[7].paragraphs[0]
        #####################################################
        run = paragraphs.add_run('   ' + thesisScore + '   ')
        run.font.underline = True
        run.font.name = '宋体'
        run.font.size = Pt(13)
        paragraphs.add_run('分')
        setStyle(row1)
        setStyle(row2)
        setFontStyle(row10)
        setFontStyle(row11)
        setFontStyle(row12)
        setFontStyle(row16)
        setFontStyle(row18)
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord'):
            os.mkdir(f'{getRunFilePath()}/GenerateWord')
        # 判断文件是否存在
        if not os.path.exists(f'{getRunFilePath()}/GenerateWord/{number}{studentName}'):
            # 文件不再存在则创建文件
            os.mkdir(f'{getRunFilePath()}/GenerateWord/{number}{studentName}')
        #####################################################
        title = title.replace('/' , '')
        document.save(os.path.join(f"{getRunFilePath()}/GenerateWord/{number}{studentName}",
                                    f'{title}.docx'))
        return f"{getRunFilePath()}/GenerateWord/{number}{studentName}/{title}.docx"

    except Exception as e:
        print(e)
        QMessageBox.critical(None, "文档生成错误", f"生成文档时出现错误：\n{str(e)}")

def setStyle(row):
    '''
    设置表格样式中的居中
    Parameters
    ----------
    row：表格中的行

    Returns
    -------
    无
    '''
    for cell in row.cells:  # 所有单元格
        for paragraph in cell.paragraphs:  # 所有段落
            paragraph.paragraph_format.alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直对齐，居中
            for run in paragraph.runs:
                font = run.font
                font.size = Pt(12)

def setFontStyle(row):
    '''
    设置表中字体大小

    Returns
    -------
    无
    '''
    for cell in row.cells:  # 所有单元格
        for paragraph in cell.paragraphs:  # 所有段落
            for run in paragraph.runs:
                font = run.font
                font.size = Pt(12)

def main(record):
    return generateWord(record)

def getRunFilePath():
    '''
    会判断是Exe可执行程序还是Python文件，获取当前执行程序的文件夹路径
    Returns
    -------
    文件执行路径
    '''
    application_path = ''
    application_path = os.path.dirname(os.path.dirname(__file__))
    return application_path

# 设置提问回答默认值
def setInitValue(current , record):
    title = record['title'].replace('/' , '')
    studentName = record['studentName']
    number = record['number']
    if os.path.exists(f'{getRunFilePath()}/GenerateWord/{number}{studentName}/{title}.docx'):
        document = Document(os.path.join(f'{getRunFilePath()}/GenerateWord/{number}{studentName}/{title}.docx'))
        table = document.tables[0]
        # 获取提问一
        request1 = table.rows[9].cells[0].text.replace('1、','')
        ask1 = table.rows[9].cells[7].text
        request2 = table.rows[10].cells[0].text.replace('2、','')
        ask2 = table.rows[10].cells[7].text
        request3 = table.rows[11].cells[0].text.replace('3、','')
        ask3 = table.rows[11].cells[7].text
        current.ui.request1.setText(request1)
        if ask1 == '正确':
            current.ui.comboBox.setCurrentIndex(0)
        elif ask1 == '基本正确':
            current.ui.comboBox.setCurrentIndex(1)
        else:
            current.ui.comboBox.setCurrentIndex(2)
        current.ui.request2.setText(request2)
        if ask2 == '正确':
            current.ui.comboBox_2.setCurrentIndex(0)
        elif ask2 == '基本正确':
            current.ui.comboBox_2.setCurrentIndex(1)
        else:
            current.ui.comboBox_2.setCurrentIndex(2)
        current.ui.request3.setText(request3)
        if ask3 == '正确':
            current.ui.comboBox_3.setCurrentIndex(0)
        elif ask3 == '基本正确':
            current.ui.comboBox_3.setCurrentIndex(1)
        else:
            current.ui.comboBox_3.setCurrentIndex(2)

# if __name__ == '__main__':
#     main()